package cate.game.chat;

import cate.game.GameBody;
import cate.game.role.Role;

import java.util.*;

public class ChatHistory {

    private final Map<Byte, List<Pair>> map = new HashMap<>();

    /** 加入新的公共聊天 */
    public void addPublic(GameBody game, ChatPublicItem item, ChatFilter filter) {
        List<Pair> itemList = getPublicList(item.channel);

        int itemMax = game.table.chat.base.getItemMax(item.channel);

        if (itemList.size() >= itemMax) {
            itemList.remove(0);
        }
        itemList.add(new Pair(item, filter));
    }

    /** 获取指定公共频道的消息列表 */
    private List<Pair> getPublicList(byte channel) {
        List<Pair> itemList = map.get(channel);
        if (itemList == null) {
            itemList = Collections.synchronizedList(new LinkedList<>());
            map.put(channel, itemList);
        }
        return itemList;
    }

    /** 获取指定公共频道的消息列表, 符合该master需求的 */
    public List<ChatPublicItem> getPublicListForMaster(byte channel, Role role) {
        List<Pair> pairList = getPublicList(channel);
        List<ChatPublicItem> fitList = new ArrayList<>();
        for (Pair pair : pairList) {
            if (pair.filter == null || pair.filter.accept(pair.item, role)) {
                fitList.add(pair.item);
            }
        }
        return fitList;
    }

    private static class Pair {
        public ChatPublicItem item;
        public ChatFilter filter;

        public Pair(ChatPublicItem item, ChatFilter filter) {
            this.item = item;
            this.filter = filter;
        }
    }
}
